<template>
  <div @click="show">
    <FormItemRest>
      <a-input
        readonly
        :disabled="disabled"
        :placeholder="placeholder"
        v-model:value="formName"
        :size="size"
        :bordered="bordered"
      >
        <template #prefix v-if="prefix">
          <Icon :icon="prefix" />
        </template>
        <template #suffix v-if="suffix">
          <Icon :icon="suffix" />
        </template>
      </a-input>

      <ModalPanel
        :visible="visible"
        :width="800"
        :title="t('表单设置')"
        @submit="submit"
        @close="close"
      >
        <template #left>
          <div class="form-category">
            <div class="tree-box" v-if="formType == 1">
              <BasicTree
                :title="t('表单分类')"
                :clickRowToExpand="true"
                :treeData="treeData"
                :fieldNames="{ key: 'id', title: 'name' }"
                @select="handleSelect"
              />
            </div>
            <div class="tree-box" v-else>
              <NodeHead class="title" :node-name="t('代码模板分类')" />
              <div class="item" :class="modelValue === 0 ? 'checked' : ''" @click="change(0)">
                <IconFontSymbol class="item-icon" icon="xitong" />
                <span class="item-text">{{ t('数据优先模板') }}</span>
              </div>
              <div class="item" :class="modelValue == 1 ? 'checked' : ''" @click="change(1)">
                <IconFontSymbol class="item-icon" icon="zidingyi" />
                <span class="item-text">{{ t('界面优先模板') }}</span>
              </div>
              <div class="item" :class="modelValue == 2 ? 'checked' : ''" @click="change(2)">
                <IconFontSymbol class="item-icon" icon="xitong" />
                <span class="item-text">{{ t('简易模板') }}</span>
              </div>
            </div>
          </div>
        </template>

        <SearchBox @search="searchList" />

        <div class="list-page-box" v-if="setting.list.length > 0">
          <FormCard
            v-for="(item, index) in setting.list"
            :key="index"
            :item="item"
            :class="selectKeys.includes(item.key) ? 'picked' : 'notPicked'"
            @click="checked(item)"
          >
            <template #check>
              <a-checkbox
                size="small"
                :checked="selectKeys.includes(item.key) ? true : false"
                :disabled="item.enabledMark == 1 ? false : true"
              />
            </template>
          </FormCard>
          <div class="page-box">
            <a-pagination
              v-model:current="setting.page.current"
              :pageSize="setting.page.pageSize"
              :total="setting.page.total"
              show-less-items
              @change="getTemplateList"
            />
          </div>
        </div>
        <EmptyBox v-else />
      </ModalPanel>
    </FormItemRest>
  </div>
</template>

<script setup lang="ts">
  import { computed, reactive, ref, watch } from 'vue';
  import { message } from 'ant-design-vue';
  import { ModalPanel, SearchBox, EmptyBox } from '/@/components/ModalPanel/index';
  import { BasicTree, TreeItem } from '/@/components/Tree';
  import FormCard from '/@bpmn/components/card/FormCard.vue';
  import { FormType } from '/@/enums/workflowEnum';
  import { FormSettingItem } from '/@/model/workflow/formSetting';
  import { getFormTemplatePage } from '/@/api/form/design';
  import { NodeHead } from '/@/components/ModalPanel/index';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { Form } from 'ant-design-vue';
  import IconFontSymbol from '/@/components/IconFontSymbol/Index.vue';
  import { Icon } from '/@/components/Icon';
  import { getCodeTemplateList } from '/@/api/system/generator';
  import { getDicDetailList } from '/@/api/system/dic';

  // 用于包裹弹窗的form组件 因为一个FormItem 只能收集一个表单组件  所以弹窗的form 必须排除
  const FormItemRest = Form.ItemRest;

  const props = defineProps({
    value: Object,
    prefix: String,
    suffix: String,
    placeholder: String,
    readonly: Boolean,
    disabled: Boolean,
    size: String,
    isSingle: Boolean,
    formType: {
      type: Number,
      default: () => 1,
    },
    list: {
      type: Array,
      default: () => [],
    },
    bordered: {
      type: Boolean,
      default: true,
    },
  });
  const { t } = useI18n();
  const treeData = ref<TreeItem[]>([]);
  let emits = defineEmits(['change']);
  const modelValue = ref(0);
  const category = ref();
  const formName = ref(props.value?.formName);

  watch(
    () => props.value,
    (val) => {
      if (val?.formName) {
        formName.value = val.formName;
      } else {
        formName.value = '';
      }
    },
    { deep: true },
  );
  const visible = ref(false);
  let setting: {
    checkFormType: FormType;
    selectedList: Array<FormSettingItem>;
    list: Array<FormSettingItem>;
    searchKeyword: string;
    page: { current: number; total: number; pageSize: number };
    formKeyList: Object;
    checkedFormId: Object;
    usedRepeatedList: Object;
    usedNotRepeatedList: Array<string>;

    operationCloneItem: FormSettingItem;
  } = reactive({
    checkFormType: FormType.CUSTOM,
    selectedList: [],
    list: [],
    searchKeyword: '',
    page: { current: 1, total: 0, pageSize: 9 },
    formKeyList: {},
    checkedFormId: {},
    usedRepeatedList: {},
    usedNotRepeatedList: [],

    operationCloneItem: {
      key: '', //formId_key
      formType: FormType.CUSTOM, //表单类型
      formId: '', //表单ID   系统表单为文件夹名
      formName: '', //表单名称
    },
  });

  let selectKeys = computed(() => {
    if (setting.selectedList && setting.selectedList.length > 0) {
      return setting.selectedList.map((ele: FormSettingItem) => {
        return ele.key;
      });
    }
    return [];
  });
  async function show() {
    setting.list = [];
    setting.page.total = 0;
    await getTemplateList();
    visible.value = true;
  }

  async function getTemplateList() {
    let res: any = {};
    if (props.formType == 1) {
      treeData.value = (await getDicDetailList({
        itemId: '1419276800524424444',
      })) as unknown as TreeItem[];
      let params = {
        limit: setting.page.current,
        size: setting.page.pageSize,
        type: props.formType,
        category: category.value,
        keyword: setting.searchKeyword,
      };
      res = await getFormTemplatePage(params);
    } else {
      let params = {
        limit: setting.page.current,
        size: setting.page.pageSize,
        type: modelValue.value,
        keyword: setting.searchKeyword,
      };
      res = await getCodeTemplateList(params);
    }
    if (res.total) {
      setting.page.total = res.total;
    }
    setting.list = [];
    if (res.list.length > 0) {
      res.list.forEach((ele) => {
        setting.list.push({
          key: ele.id,
          formType: props.formType,
          formName: ele.name ? ele.name : ele.id,
          formId: props.formType == 1 ? ele.id : ele.formId,
          enabledMark: ele.status || 1,
        });
      });
    }
  }
  function change(type) {
    modelValue.value = type;
    getTemplateList();
  }
  function handleSelect(selectIds) {
    category.value = selectIds[0];
    getTemplateList();
  }
  async function submit() {
    if (setting.selectedList.length === 0) {
      message.error(t('请至少选择一个表单'));
      return false;
    }
    //formName.value = setting.selectedList[0].formName;
    emits('change', setting.selectedList[0]);
    close();
  }
  function close() {
    visible.value = false;
  }
  async function searchList(keyword: string) {
    setting.searchKeyword = keyword;
    setting.page.current = 1;
    await getTemplateList();
  }
  function checked(item: FormSettingItem) {
    if (item.enabledMark != 1) return;

    if (props.isSingle) {
      // 单选

      setting.selectedList = [item];
    } else {
      // 多选
      let index = setting.selectedList.findIndex((ele) => {
        return ele.key === item.key;
      });
      if (index >= 0) {
        setting.selectedList.splice(index, 1);
      } else {
        setting.selectedList.push(item);
      }
    }
  }
</script>

<style lang="less" scoped>
  .page-box {
    position: absolute;
    bottom: 80px;
    right: 20px;
  }

  .picked {
    border-width: 1px;
    border-style: dotted;
  }

  .notPicked {
    border-width: 1px;
    border-style: dotted;
    border-color: transparent;
  }

  .form-category {
    .title {
      height: 40px;
      font-size: 16px;
      color: #333;
      border-bottom: 1px solid #f0f0f0;
    }

    .tree-box {
      padding: 10px 0;

      .item {
        display: flex;
        align-items: center;
        height: 40px;
        font-size: 14px;
        color: #606266;
        padding: 10px;

        .item-icon {
          font-size: 14px;
          color: #606266;
        }

        .item-text {
          margin-left: 20px;
        }
      }

      .checked {
        background: #e5f1ff;
      }
    }
  }
</style>
